package com.ecjtu.stadiumre_servations.service.impl;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecjtu.stadiumre_servations.entity.domain.Booking;
import com.ecjtu.stadiumre_servations.entity.domain.Student;
import com.ecjtu.stadiumre_servations.entity.domain.User;
import com.ecjtu.stadiumre_servations.entity.dto.LoginDTO;
import com.ecjtu.stadiumre_servations.entity.dto.UserDTO;
import com.ecjtu.stadiumre_servations.mapper.StudentMapper;
import com.ecjtu.stadiumre_servations.mapper.UserMapper;
import com.ecjtu.stadiumre_servations.response.Result;
import com.ecjtu.stadiumre_servations.response.ResultCodeEnum;
import com.ecjtu.stadiumre_servations.service.StudentService;
import com.ecjtu.stadiumre_servations.service.UserService;
import com.ecjtu.stadiumre_servations.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User>implements UserService{
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public Result register(UserDTO userDTO) {
        if (!studentService.isUserExistsInStudent(userDTO)){
            return Result.fail("不存在学号为"+userDTO.getUsername()+"的学生");
        }
        User user1 = getOne(Wrappers.<User>lambdaQuery().eq(User::getIdCard,userDTO.getIdCard())); // 身份证号
        User user2 = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername,userDTO.getUsername())); // 学号
        if (user1!=null||user2!=null){
            return Result.fail("该学生已绑定");
        }

        if (userDTO.getUsername()==null||userDTO.getPassword()==null||userDTO.getIdCard()==null||userDTO.getPhone()==null){
            return Result.fail("请填写完整的用户信息");
        }
        if (!studentService.isUserIdCardCorrect(userDTO)){
            return Result.fail("学生身份证信息错误");
        }
        User user = new User();
        String randomUUID = UUID.randomUUID().toString();
        user.setUsername(userDTO.getUsername());
        user.setPassword(userDTO.getPassword());
        user.setSalt(randomUUID);
        user.setPhone(userDTO.getPhone());
        user.setIdCard(userDTO.getIdCard());
        user.setPassword(DigestUtils.md5DigestAsHex((userDTO.getPassword()+ randomUUID).getBytes()));
        user.setUserType("用户");
        save(user);

        return Result.ok("创建用户成功");
    }

    @Override
    public Result login(LoginDTO loginDTO) {
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername,loginDTO.getUsername()));
        if (user==null){
            return Result.fail("登陆失败，该用户不存在");
        }
        String salt = user.getSalt();
        String password = loginDTO.getPassword();
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex((password+salt).getBytes()))){
            return Result.fail("账号或密码错误");
        }
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            return Result.fail("用户名和密码不能为空");
        }
        // 登录成功，生成Token
        String token = JwtUtils.generateToken(user.getUsername());
        Student student = studentMapper.selectById(user.getUsername());
        String name = student.getName();

//        return Result.ok("登陆成功");
//                .data("user", user)
//                .data("token", token);
        Map<String, Object> data = new HashMap<>();
        data.put("user", user);
        data.put("name",name);
        data.put("token", token);
        return Result.ok(data, ResultCodeEnum.SUCCESS).message("登陆成功");
    }

    @Override
    public Result updatePassword(String oldPassword, String newPassword) {
        // 从请求头中获取 JWT Token
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");
        System.out.println("Token: " + token);
        String username = JwtUtils.getUsernameFromToken(token);
        if (token == null || username == null) {
            return Result.fail("Token 解析失败");
        }
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        System.out.println("User: " + user);
        // 检查用户是否存在
        if (user == null) {
            return Result.fail("用户不存在");
        }
        // 计算旧密码的加盐MD5值
        String encryptedOldPassword = DigestUtils.md5DigestAsHex((oldPassword + user.getSalt()).getBytes());
        // 检查两次密码是否一致（比较明文，用户体验更好）
        if (oldPassword.equals(newPassword)) {
            return Result.fail("新密码不能与旧密码相同");
        }
        // 检查旧密码是否正确（比较加密后的哈希值）
        if (!encryptedOldPassword.equals(user.getPassword())) {
            return Result.fail("旧密码错误");
        }
        // 生成新的盐值
        String newSalt = UUID.randomUUID().toString().substring(0, 6);
        // 计算新密码的加盐MD5值
        String encryptedNewPassword = DigestUtils.md5DigestAsHex((newPassword + newSalt).getBytes());
        // 更新密码和盐值
        user.setPassword(encryptedNewPassword);
        user.setSalt(newSalt);
        boolean success = updateById(user);
        if (success) {
            return Result.ok("密码更新成功");
        } else {
            return Result.fail("密码更新失败");
        }
    }
    @Override
    public Result updatePhone(String oldPhone, String newPhone) {
        // 从请求头中获取 JWT Token
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");
        if (token==null) {
            return Result.fail("Token 解析失败");
        }

        // 从 Token 中解析出用户名
        String username = JwtUtils.getUsernameFromToken(token);
        if (username == null) {
            return Result.fail("Token 解析失败");
        }
        // 根据用户名查询用户信息
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));

        // 检查用户是否存在
        if (user == null) {
            return Result.fail("用户不存在");
        }
        // 检查新旧手机号是否相同
        if (oldPhone.equals(newPhone)) {
            return Result.fail("新旧手机号一致");
        }
        // 检查旧手机号是否正确
        if (!user.getPhone().equals(oldPhone)) {
            return Result.fail("旧手机号错误");
        }
        // 检查新手机号是否已被其他用户使用
        User existingUserWithNewPhone = getOne(Wrappers.<User>lambdaQuery().eq(User::getPhone, newPhone));
        if (existingUserWithNewPhone != null) {
            return Result.fail("新手机号已被其他用户使用");
        }

        // 更新手机号
        user.setPhone(newPhone);
        boolean success = updateById(user);

        if (success) {
            return Result.ok("手机号更新成功");
        } else {
            return Result.fail("手机号更新失败");
        }
    }
}

